package io.clayton.miep.core;

import io.clayton.miep.utils.FieldUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.mybatis.spring.support.SqlSessionDaoSupport;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public abstract class DefaultServiceImpl<VO extends BaseVO> extends SqlSessionDaoSupport implements BaseService<VO> {
	
	/**
	 * 保存对象
	 * @param vo
	 * @return
	 */
	public int save(VO vo) {
		FieldUtils.setFieldValue(vo, FieldUtils.INSERT);
		return getSqlSession().insert(getMapper() + ".insertSelective", vo);
	};

	/**
	 * 更新对象
	 * @param vo
	 * @return
	 */
	public int modify(VO vo) {
		FieldUtils.setFieldValue(vo, FieldUtils.UPDATE);
		return getSqlSession().update(getMapper() + ".updateByPrimaryKeySelective", vo);
	};

	/**
	 * 删除对象(SQL id为deleteByPrimaryKey)
	 * @param id
	 * @return
	 */
	public int delete(String id) {
		return getSqlSession().delete(getMapper() + ".deleteByPrimaryKey", id);
	};

	/**
	 * 批量删除对象(id为delete)
	 * @param id
	 * @return
	 */
	public int delete(String[] id) {
		return getSqlSession().delete(getMapper() + ".delete", id);
	};

	/**
	 * 获取对象
	 * @param id
	 * @return
	 */
	public VO get(String id) {
		return getSqlSession().selectOne(getMapper() + ".getByPrimaryKey", id);
	};

	/**
	 * 查询单个对象(SQL要自己写 id必须为getOne)
	 * @param id
	 * @return
	 */
	public VO findOne(Map<? extends Object, ? extends Object> map) {
		return getSqlSession().selectOne(getMapper() + ".getOne", map);
	};
	
	
	/**
	 * 列出全部对象并分页显示(SQL要自己写 id必须为getWithPaging 参数名为start，length)
	 * @param start
	 * @param length
	 * @return
	 */
	public List<VO> findWithPaging(int start, int length) {
		Map<String, Integer> param = new HashMap<String, Integer>();
		param.put("start", start);
		param.put("length", length);
		return getSqlSession().selectList(getMapper() + ".getWithPaging", param);
	};
	
	/**
	 * 查询对象(SQL要自己写 id必须为gets)
	 * @param param
	 * @return
	 */
	public List<VO> find(Map<Object, Object> param) {
		return getSqlSession().selectList(getMapper() + ".gets", param);
	};
	
	/**
	 * 查询对象并分页显示(SQL要自己写 id必须为getWithPaging2 参数名为start，length)
	 * @param map
	 * @param start
	 * @param length
	 * @return
	 */
	public List<VO> findWithPaging(Map<Object, Object> map, int start, int length) {
		map.put("start", start);
		map.put("length", length);
		return getSqlSession().selectList(getMapper() + ".getWithPaging2", map);
	};
	
	/**
	 * 获取所有对象
	 * @return
	 */
	public List<VO> findAll(){
		return getSqlSession().selectList(getMapper() + ".getAll");
	}
	
	/**
	 * 设置Mapper的namespace
	 * @return
	 */
	public abstract String getMapper();
}
